import Taro from '@tarojs/taro';
import { connect } from 'react-redux'
import Storage from '@UTILS/storage';
import profileActions from '@ACTIONS/profile'
import authActions from '@ACTIONS/auth'
import Navigate from '@NAVIGATION/navigateManager'
import { commonInitUser } from '@UTILS/user'

const LIFE_CYCLE_MAP = ['willMount', 'didMount', 'didShow'];

function withLogin(lifecycle = 'didMount') {
  // 异常规避提醒
  if (LIFE_CYCLE_MAP.indexOf(lifecycle) < 0) {
    console.warn(
      `传入的生命周期不存在, 鉴权判断异常 ===========> ${lifecycle}`
    );
    return Component => Component;
  }

  return function withLoginComponent(Component) {
    // 避免H5兼容异常
    if (Taro.getEnv() !== Taro.ENV_TYPE.WEAPP) {
      return Component;
    }

    // 这里还可以通过redux来获取本地用户信息，在用户一次登录之后，其他需要鉴权的页面可以用判断跳过流程
    @connect(({ profile }) => ({
      user: profile.user,
      isVisitor: profile.isVisitor
    }),
    { ...profileActions, ...authActions })
    class WithLogin extends Component {
      async componentDidMount() {
        const { user } = this.props
        !user && await this.initUser()
        if (super.componentDidMount) {
          if (lifecycle === LIFE_CYCLE_MAP[1]) {
            const res = await this.checkToken();
            if (!res) return;
            await super.componentDidMount();
          } else {
            super.componentDidMount();
          }
        }
      }

      async componentDidUpdate(prevProps, prevState) {
        const { isVisitor } = this.props
        if (!isVisitor && prevProps.isVisitor) {
          super.componentDidMount && super.componentDidMount()
          return
        }
        if (!isVisitor) {
          super.componentDidUpdate && super.componentDidUpdate(prevProps, prevState)
        }
      }

      async checkToken() {
        await Storage.getInstance().initModel();
        const token = Storage.getInstance().getToken();
        const { isVisitor } = this.props
        if ((!token || token.length <= 0) || isVisitor) {
          await Navigate.authPage()
          return false;
        }
        return true;
      }

      async initUser() {
        const { dispatchInitUser, dispatchVisitorLogin } = this.props
        commonInitUser(dispatchInitUser, dispatchVisitorLogin)
      }
    }
    return WithLogin
  }
}

export default withLogin;
